import csv
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler

plt.rcParams['font.family'] = ['sans-serif']
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

csv_data = []
with open('economic_indicators.csv', newline='', encoding='utf-8') as csv_file:
    csv_reader = csv.reader(csv_file)
    for row in csv_reader:
        csv_data.append(row[:])

if __name__ == '__main__':
    # 标准化处理
    features = np.array(csv_data)[:, 1:].astype(float)
    print("特征矩阵:\n", features)
    standard_scaler = StandardScaler()
    features_normalized = standard_scaler.fit_transform(features)
    # 计算协方差矩阵
    cov_matrix = np.cov(features_normalized, rowvar=False)
    print("协方差矩阵:\n", cov_matrix)
    # 计算协方差矩阵的特征值和特征向量
    eigenvalues, eigenvectors = np.linalg.eig(cov_matrix)
    # 特征值从大到小排序
    sorted_indices = np.argsort(eigenvalues)[::-1]
    # 计算累计方差贡献率 (由于此题中明确要求降至两维, 实质上累计方差贡献率可以不再求解)
    variance_ration = np.cumsum(eigenvalues[sorted_indices] / np.sum(eigenvalues))
    print("方差贡献率:\n", eigenvalues[sorted_indices] / np.sum(eigenvalues))
    print("累计方差贡献率:\n", variance_ration)
    # 取前 2 个特征向量构成特征矩阵 P
    P = eigenvectors[:, sorted_indices[:2]]
    # 计算降维后的数据
    reduced_features = np.dot(features_normalized, P)
    print("降维后的特征矩阵:\n", reduced_features)
    # 绘制结果图
    plt.figure(figsize=(8, 6))
    plt.scatter(reduced_features[:, 0], reduced_features[:, 1])
    plt.title('PCA of Economic Indicators')
    plt.xlabel('Principal Component 1')
    plt.ylabel('Principal Component 2')
    # 求出经济发展最佳省份
    best_province_index = np.argmax(np.abs(reduced_features[:, 0] * reduced_features[:, 1]))
    best_province = csv_data[best_province_index][0]
    plt.annotate(f'Best Province: {best_province}',
                 xy=(reduced_features[best_province_index, 0], reduced_features[best_province_index, 1]),
                 xytext=(-30, 30), textcoords='offset points',
                 arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.5', color='red'))
    plt.show()
